import web, datetime
import json, time
import subprocess 

import os
import re
import logging
import logging.handlers

my_logger = logging.getLogger('MyLogger')
my_logger.setLevel(logging.DEBUG)
handler = logging.handlers.SysLogHandler(address = '/dev/log')
my_logger.addHandler(handler)

class Wifi2:
    def __init__(self, id):
        self.id = id
        
    @staticmethod
    def scan():
        args = ("connmanctl scan wifi").split()
        try:
            ret = subprocess.check_output(args)        
            logging.warning(ret)
            if ret.strip() == "Scan completed for wifi":
                return True
            return False
        except OSError:
            return False

    @staticmethod
    def get_ssids():
        args = ("connmanctl services").split()
        
        ssids = []
        try:
            ret = subprocess.check_output(args)        
            for line in ret.split("\n"):
                m = re.search('^([A|O|\*]*)\s+(\w*)\s+(wifi_\w+)', line)            
                if m:
                    logging.warning(m.group(1))
                    ssids.append(
                    {"name": m.group(2), 
                    "id": m.group(3),
                    "connected": True if "O" in m.group(1) else False,
                    "associated": True if "A" in m.group(1) else False, 
                    "in_use": True if "*" in m.group(1) else False})
        except OSError:
            ssids.append("Error in scan")
        return ssids    
    
    def id_valid(self):
        #TODO: implement this
        ''' Returns true if the id is in the list of services'''
        return True

    def connect(self):
        args = ["connmanctl", "connect", self.id]
        try:
            ret = subprocess.check_output(args)        
        except OSError:
            return False
        return True

    def is_connected(self):
        #TODO: implement this
        return True

    def wpa_password(self, ssid, password):
        args = ["wpa_passphrase", ssid, password]
        try:
            ret = subprocess.check_output(args)      
            for line in ret.split("\n"):
                if "psk=" in line and not "#psk=" in line:
                    return line.split("=")[1]
        except OSError:
            return False
        return False

    def write_config(self, id, ssid, passwd):
        psk = self.wpa_password(ssid, passwd)        
        path = "/var/lib/connman/"+id+".config"
        with open(path, "w+") as f:
            f.write("[service_"+id+"]\n")
            f.write("Type = wifi\n")
            f.write("Name = "+ssid+"\n")
            f.write("Passphrase = "+psk)

